import { useRef, useEffect, useMemo, useState, forwardRef, useImperativeHandle } from 'react';
import _ from 'lodash';
import { Input } from '@formily/antd';
import { createForm } from '@formily/core';
import { FormProvider, createSchemaField } from '@formily/react';
import { getPageMeta } from '@/services/request/meta';
import component from '@/components/schema-form-render/schema-components-registed/components-biz';
import initialArrayTableSchema from '@/components/schema-form-render/until';
import { IEditTable as Iporps } from './schema';

import { merge } from 'lodash';

export default forwardRef((props: Iporps, ref) => {
  const {
    pageCode,
    serial = false,
    dataSource = [],
    type = 'NORMAL',
    filedConfig,
    formConfigs,
    filed,
    tableProps,
    eventMap,
  } = props;

  const [meta, setMeta] = useState<any>();
  const form = useMemo(() => createForm(formConfigs), [formConfigs]);

  useImperativeHandle(ref, () => {
    return { form };
  });
  const SchemaField = useMemo(
    () =>
      createSchemaField(
        _.merge({
          components: {
            Input,
            ...component,
          },
          filedConfig,
        }),
      ),
    [filedConfig],
  );
  // 编辑设置默认值
  useEffect(() => {
    if (dataSource.length) {
      form.setValues({ array: dataSource });
    }
  }, [JSON.stringify(dataSource)]);
  useEffect(() => {
    getPageMeta(pageCode).then((res: any) => {
      const schema = initialArrayTableSchema(res?.result, type, serial, filed, {
        nNeedAddition: false
      }, eventMap);

      if (schema[filed]['x-component-props'] && tableProps) {
        schema[filed]['x-component-props'] = merge(schema[filed]['x-component-props'], tableProps);
      }
``
      setMeta({
        type: 'object',
        properties: schema,
      });
    });
  }, [pageCode]);

  console.log('meta', meta);
  return (
    <FormProvider form={form}>
      <SchemaField schema={meta || {}} />
    </FormProvider>
  );
});
